package com.starrtc.demo.imclient.clientHandler;

import com.starrtc.demo.imclient.client.ClientSession;
import com.starrtc.demo.imclient.client.Controller;
import com.starrtc.demo.imclient.iMcommon.exception.InvalidFrameException;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * create by 尼恩 @ 疯狂创客圈
 **/
@ChannelHandler.Sharable
public class ExceptionHandler extends ChannelInboundHandlerAdapter {

    public static ExceptionHandler instance;

    public static ExceptionHandler getInstance(){
        if(instance == null){
            instance = new ExceptionHandler();
        }
        return instance;
    }

    private ExceptionHandler() {
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // ..

        if (cause instanceof InvalidFrameException) {
//            log.error(cause.getMessage());
            ClientSession.getSession(ctx).close();
        } else {

            //捕捉异常信息
//             cause.printStackTrace();
//            log.error(cause.getMessage());
            ctx.close();

            //开始重连
            Controller.getInstance().setConnectFlag(false);
            Controller.getInstance().startConnectServer();
        }
    }

    /**
     * 通道 Read 读取 Complete 完成
     * 做刷新操作 ctx.flush()
     */
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

}